<template>
  <div>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48" @keyup.enter.native="searchList">
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="资源位id">
                <a-input v-model="queryParam.id" placeholder="请输入活动名称或标记名称" allowClear />
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="标题">
                <a-input v-model="queryParam.titleTxt" placeholder="请输入标题名称" allowClear />
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="小程序">
                <a-select v-model="queryParam.appId" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option value="">不限</a-select-option>
                  <a-select-option :value="item.appId" v-for="item in env === 'production' ? brandListPro : brandList" :key="item.appId">{{ item.brandName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="位置">
                <a-select v-model="queryParam.position" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option value="">不限</a-select-option>
                  <a-select-option :value="item.code" :key="index" v-for="(item, index) in positionList">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="显示时间">
                <a-select v-model="queryParam.showTimeType" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option value="">不限</a-select-option>
                  <a-select-option :value="1">按用户生日</a-select-option>
                  <a-select-option :value="0">自定义时间</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24" v-if="queryParam.showTimeType === 0">
              <a-form-item label="自定义时间">
                <a-range-picker
                  style="width: 100%"
                  :show-time="{
                    hideDisabledOptions: true,
                    defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')]
                  }"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="['开始时间', '结束时间']"
                  v-model="queryParam.timePicker"
                />
              </a-form-item>
            </a-col>
            <a-col :sm="24">
              <a-button style="margin-left: 8px; float: left" type="primary" ghost @click="handleChannel">资源位管理</a-button>
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="searchList">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetList">重置</a-button>
                <a-button style="margin-left: 8px" type="primary" icon="plus" @click="handleAdd">新建</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-tabs :activeKey="queryParam.status" @change="tabsChange">
        <a-tab-pane :key="1" :tab="`进行中`"></a-tab-pane>
        <a-tab-pane :key="0" :tab="`未开始`" forceRender></a-tab-pane>
        <a-tab-pane :key="2" :tab="'已结束'" forceRender></a-tab-pane>
      </a-tabs>
      <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }">
        <span slot="remark" slot-scope="text">
          <ellipsis :length="16" tooltip style="color: #40a9ff">{{ text }}</ellipsis>
        </span>
        <span slot="image" slot-scope="text">
          <img :src="text" class="coverimg" @click="handlePreview(text)" />
        </span>
        <span slot="action" slot-scope="text, record">
          <router-link :to="`/micromall/personalCenter/channel/edit/${record.id}`" v-if="queryParam.status == 2">查看</router-link>
          <router-link :to="`/micromall/personalCenter/channel/edit/${record.id}`" v-else>编辑</router-link>
          <a-divider type="vertical" />
          <router-link :to="`/micromall/personalCenter/channel/edit/${record.id}/copy`">复制</router-link>
          <template v-if="queryParam.status != 2">
            <a-divider type="vertical" />
            <a-popconfirm title="确定下架吗?" ok-text="Yes" cancel-text="No" @confirm="handleEnable(record, 1)" v-if="queryParam.status == 1">
              <a href="#">下架</a>
            </a-popconfirm>
            <a-popconfirm title="确定上架吗?" ok-text="Yes" cancel-text="No" @confirm="handleEnable(record, 0)" v-if="queryParam.status == 0">
              <a href="#">上架</a>
            </a-popconfirm>
          </template>
        </span>
      </s-table>
      <ChannelModal ref="channelModal"></ChannelModal>
      <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </a-card>
  </div>
</template>
<script>
import moment from 'moment'
import 'moment/locale/zh-cn'
import { posTemplateList, posTemplateUpOrDown } from '@/api/marketingCenter/memberTask'
import { listMixin } from '@/views/box/util/listMixin'
import { mixin } from './mixin'
import ChannelModal from './module/channelModal'

let columns = [
  { title: '资源位id', dataIndex: 'id' },
  { title: '小程序', dataIndex: 'appName', width: 170 },
  { title: '位置', dataIndex: 'posManagerName', width: 170 },
  { title: '图片', dataIndex: 'image', scopedSlots: { customRender: 'image' }, width: 100 },
  { title: '排序', dataIndex: 'sortNo', width: 100, customRender: (t, r) => (r.position == 1 ? '-' : t) },
  { title: '标题', dataIndex: 'titleTxt', width: 150, customRender: (t, r) => (r.position == 2 ? t : '-') },
  { title: '备注', dataIndex: 'remark', scopedSlots: { customRender: 'remark' } },
  { title: '显示时间', customRender: (t, r) => (r.showTimeType === 0 ? `${r.startTime}~${r.endTime}` : r.birthdayTime == 1 ? '仅生日当月' : '生日前一个月至生日月结束') },
  { title: '操作', fixed: 'right', width: 150, align: 'center', scopedSlots: { customRender: 'action' } }
]
export default {
  mixins: [listMixin, mixin],
  components: { ChannelModal },
  data() {
    return {
      columns,
      queryParam: {
        status: 1,
        appId: '',
        position: '',
        showTimeType: ''
      },
      loadData: parameter => this.fetchData(parameter),
      previewVisible: false,
      previewImage: '',
      env: process.env.NODE_ENV
    }
  },
  watch: {
    $route(to, from) {
      let editPath = '/micromall/personalCenter/channel/edit'
      let currentPath = this.$route.path
      if (from.path.includes(editPath) && to.path == currentPath) {
        this.$refs.table.refresh()
      } else if (from.path.includes(currentPath) || to.path.includes(editPath)) {
      } else {
        if (from.path.includes('/micromall/personalCenter/channel/') && !to.path.includes('/micromall/personalCenter/channel/')) {
          this.$destroy()
        }
      }
    }
  },
  methods: {
    moment,
    tabsChange(key) {
      this.queryParam.status = key
      this.$refs.table.refresh(true)
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    filterFields(values) {
      const formValue = {}
      Object.keys(values).forEach(i => {
        if (values[i] !== '' && values[i] !== undefined) {
          if (i === 'timePicker') {
            if (values[i].length) {
              formValue.startTime = values[i][0]
              formValue.endTime = values[i][1]
            }
          } else {
            formValue[i] = values[i]
          }
        }
      })
      return formValue
    },
    fetchData(parameter) {
      let formValue = this.filterFields(this.queryParam)
      let params = {
        page: parameter,
        requestData: formValue
      }
      try {
        return this.fetchList(params, posTemplateList).then(res => {
          if (res.code == 0) {
            return {
              data: res.data,
              page: res.page
            }
          } else {
            return {
              data: [],
              page: {
                pageNo: 1,
                pageSize: 10,
                count: 0
              }
            }
          }
        })
      } catch (err) {
        console.log(err.response)
      }
    },
    resetList() {
      this.queryParam = {
        status: 1,
        position: '',
        showTimeType: '',
        appId: ''
      }
      this.$refs.table.refresh(true)
    },
    handleEnable(record, status) {
      let params = {
        requestData: {
          id: record.id,
          enableStatus: status
        }
      }
      posTemplateUpOrDown(params).then(res => {
        if (res.code == 0) {
          this.$message.success('修改成功')
          this.$refs.table.refresh()
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleAdd() {
      this.$router.push('/micromall/personalCenter/channel/edit/add')
    },
    handleChannel() {
      this.$refs.channelModal.show()
    },
    handlePreview(url) {
      this.previewImage = url
      this.previewVisible = true
    }
  }
}
</script>

<style lang="less" scoped>
.coverimg {
  display: block;
  margin: 2px auto;
  width: 60px;
  height: 60px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
  cursor: pointer;
}
</style>

